<template>
  <div :class="$style.wrapper">
    <Treeselect
      v-model="depId"
      :disabled="disabled"
      :default-expand-level="1"
      :options="$store.state.options.deptTree"
      :show-count="true"
      placeholder="请选择归属部门"
      @input="onSelectChange"
      appendToBody
      :zIndex="9999" />
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: 'DeptSelect',
  components: { Treeselect },
  model: {
    prop: 'value',
    event: 'change',
  },
  props: {
    /**
     * 字表的值，{key:value}的格式
     */
    value: null,
    /**
     * 是否只读
     */
    disabled: {
      type: Boolean,
      default: false,
    },
    width: {
      type: String,
      default: '50%',
    },
    height: {
      type: [String, Number],
      default: '300',
    },
  },
  data() {
    return {
      visible: false,
      loading: false,
      depId: null,
      deptOptions: undefined,
    }
  },
  watch: {
    value(val) {
      this.depId = val
    },
  },
  created() {
    this.depId = this.value
    this.getTreeselect()
  },
  methods: {
    onSelectChange(e, ...a) {
      this.$emit('change', e)
      setTimeout(() => {
        this.dispatch('ElFormItem', 'el.form.change', e)
      })
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      if (!this.$store.state.options.deptTree[0]) {
        this.loading = true
        dispatch('GetDeptTree').then((res) => {
          this.loading = false
        })
      }
    },

    dispatch(componentName, eventName, params) {
      var parent = this.$parent || this.$root
      var name = parent.$options.componentName

      while (parent && (!name || name !== componentName)) {
        parent = parent.$parent

        if (parent) {
          name = parent.$options.componentName
        }
      }
      if (parent) {
        parent.$emit.apply(parent, [eventName].concat(params))
      }
    },
  },
}
</script>
<style module lang="scss">
.wrapper {
}
</style>
<style>
.vue-treeselect__menu-container {
  font-size: 14px;
}
</style>
